package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ApUserSearchServiceImpl apUserSearchService;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if(StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        PageRequest pageable = PageRequest.of( dto.getPage().intValue() - 1, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(queryBuilder, pageable);
        apUserSearchService.saveUserSearch(UserThreadLocalUtil.get().getUserId(),dto.getEquipmentId(),dto.getSearchWords());
        return ResponseResult.okResult(searchPage.getContent());
    }
}
